<template>
  <div class="dashboard-editor-container">
    <el-row :gutter="40">
      <el-col :sm="24" :xs="24" :md="8" :xl="8" :lg="8" :style="{ marginBottom: '12px' }">
        <div @click="queryAllList">
          <chart-card
            title="申请总数"
            :total="dashboardValue.count.all"
            style="cursor: pointer"
            background="rgb(77, 112, 255)"
          >
            <img slot="icon" src="@/assets/all.png" alt="">
          </chart-card>
        </div>

      </el-col>

      <el-col :sm="24" :xs="24" :md="8" :xl="8" :lg="8" :style="{ marginBottom: '12px' }">
        <div @click="queryCompleteList">
          <chart-card
            title="已完成"
            :total="dashboardValue.count.complete"
            style="cursor: pointer"
            background="rgb(103, 194, 58)"
          >
            <img slot="icon" src="@/assets/complete.png" alt="">
          </chart-card>
        </div>

      </el-col>
      <el-col :sm="24" :xs="24" :md="8" :xl="8" :lg="8" :style="{ marginBottom: '12px' }">
        <div @click="queryProcessList">
          <chart-card
            title="进行中"
            :total="dashboardValue.count.process"
            style="cursor: pointer"
            background="rgb(230, 162, 60)"
          >
            <img slot="icon" src="@/assets/process.png" alt="">
          </chart-card>
        </div>
      </el-col>
    </el-row>

    <el-card class="box-card">
      <el-form ref="listQuery" :model="listQuery" :inline="true">
        <el-form-item label="项目名称" prop="title">
          <el-input
            v-model="listQuery.title"
            placeholder="请输入项目名称"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectNo">
          <el-input
            v-model="listQuery.projectNo"
            placeholder="请输入项目编号"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="项目分类" prop="projectClassify">
          <el-select
            v-model="listQuery.projectClassify"
            placeholder="请选择项目分类"
            size="small"
            clearable
            style="width: 180px"
            @change="getList"
          >
            <el-option label="非限制类" value="非限制类" />
            <el-option label="限制类" value="限制类" />
            <el-option label="上海首家" value="上海首家" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="负责人姓名" prop="leaderName">
          <el-input
            v-model="listQuery.leaderName"
            placeholder="请输入负责人"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="getList"
          />
        </el-form-item> -->
        <el-form-item label="科室" prop="applyDepart">
          <el-input
            v-model="listQuery.applyDepart"
            placeholder="请输入科室"
            clearable
            size="small"
            style="width: 180px"
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="审批状态" prop="nodeName">
          <el-select
            v-model="listQuery.nodeName"
            placeholder="请选择审批状态"
            size="small"
            clearable
            style="width: 180px"
            @change="getList"
          >
            <el-option label="科室负责人审批" value="科室负责人审批" />
            <el-option label="初审" value="初审" />
            <el-option label="项目编号填写" value="项目编号填写" />
            <el-option label="组织评审" value="组织评审" />
            <el-option label="院内评审" value="院内评审" />
            <el-option label="评审汇总" value="评审汇总" />
            <el-option label="院外评审材料" value="院外评审材料" />
            <el-option label="院外评审/备案结果" value="院外评审/备案结果" />
            <el-option label="收费价格开通" value="收费价格开通" />
            <el-option label="结束" value="结束" />
          </el-select>
        </el-form-item>

        <el-form-item label="上报时间">
          <el-date-picker
            v-model="timeValue"
            clearable
            size="small"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            @change="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="el-icon-download" size="small" @click="handleExportList">导出全部</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        border
        :data="ticketList"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="#" type="index" width="80" align="center" />
        <el-table-column label="项目名称" prop="title" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="项目编号" prop="projectNo" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="项目分类" :show-overflow-tooltip="true" align="center" width="120">
          <template slot-scope="scope">
            <span>
              {{ formatProjectClassify(scope.row.form_data) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="负责人姓名" :show-overflow-tooltip="true" align="center" width="120">
          <template slot-scope="scope">
            <span>
              {{ formatLeaderName(scope.row.form_data) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="科室" :show-overflow-tooltip="true" align="center" width="120">
          <template slot-scope="scope">
            <span>
              {{ formatDepartName(scope.row.form_data) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 2">
              已撤回申请
            </span>
            <span v-else>
              {{ scope.row.state_name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="上报人" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createUsers }}</span>
          </template>
        </el-table-column>

        <el-table-column label="上报时间" align="center" prop="create_time" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="500" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-check"
              @click="handleNsView(scope.row)"
            >阶段评审记录</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleView(scope.row)">表单数据</el-button>
            <!-- <el-button
              v-if="scope.row.is_end === 0"
              size="mini"
              type="text"
              icon="el-icon-position"
              @click="handleInversion(scope.row)"
              >转交</el-button
            > -->
            <el-button
              v-if="scope.row.is_end === 0"
              size="mini"
              type="text"
              icon="el-icon-refresh-left"
              :disabled="recallDisabled"
              @click="recallOrder(scope.row)"
            >撤回</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-time"
              @click="handleHistoryView(scope.row)"
            >审批历史</el-button>
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleExport(scope.row)"
              >导出此行</el-button
            > -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="del-btn"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog width="400px" custom-class="techDialog" title="阶段评审记录" :visible.sync="nsVisible">
        <div class="flex flex-column align-left">
          <el-link
            v-for="(item, index) in currentNs"
            :key="index"
            type="primary"
            :underline="false"
            class="font16 mt10"
          >第{{
            index + 1 }}次阶段评审:
            {{ parseTime(item.complete_time) }}</el-link>
        </div>
      </el-dialog>

      <el-dialog title="转交" :visible.sync="dialogVisible" width="30%">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm">
          <el-form-item label="节点" prop="node_id">
            <el-select v-model="ruleForm.node_id" placeholder="选择节点" size="small" style="width: 100%">
              <el-option v-for="(item, index) in nodeList" :key="index" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户" prop="user_id">
            <el-select v-model="ruleForm.user_id" filterable placeholder="选择用户" size="small" style="width: 100%">
              <el-option v-for="(item, index) in users" :key="index" :label="item.nickName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="ruleForm.remarks" type="textarea" size="small" />
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <HistoryDialog ref="historyDialog" />
    <ReviewDialog ref="reviewDialog" @refreshTable="getList" />
  </div>
</template>

<script>
import {
  workOrderList,
  unityWorkOrder,
  recallWorkOrder,
  inversionWorkOrder,
  recyclingWorkOrder
} from '@/api/xjs/work-order'
import { listAllUser } from '@/api/system/sysuser'
import HistoryDialog from '@/views/xjsxxm/components/history'
import ReviewDialog from '@/views/xjsxxm/apply/components/review'
// 搜索
import WorkOrderSearch from './components/search/index'
import ChartCard from './components/ChartCard'

import { projectData } from '@/api/dashboard'
import { formatJson } from '@/utils'
export default {
  name: 'DashboardAdmin',
  components: {
    ChartCard,
    WorkOrderSearch,
    HistoryDialog,
    ReviewDialog
  },
  data() {
    return {
      timeValue: '',
      dashboardValue: {
        count: {}
      },
      recallDisabled: false,
      users: [],
      userMap: {},
      nodeList: [],
      nsVisible: false,
      dialogVisible: false,
      queryParams: {},
      total: 0,
      loading: false,
      ticketList: [],
      currentNs: [],
      listQuery: {
        title: '',
        projectNo: '',
        projectClassify: '',
        leaderName: '',
        applyDepart: '',
        nodeName: '',
        page: 1,
        per_page: 10
      },
      ruleForm: {
        work_order_id: '',
        node_id: '',
        user_id: '',
        remarks: ''
      },
      rules: {
        node_id: [{ required: true, message: '请选择节点', trigger: 'change' }],
        user_id: [{ required: true, message: '请选择用户', trigger: 'change' }]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  created() {
    this.initUsers()
  },
  methods: {
    handleNsView(row) {
      if (
        row.ProjectAnnuals &&
        row.ProjectAnnuals != null &&
        row.ProjectAnnuals.length > 0
      ) {
        row.ProjectAnnuals = row.ProjectAnnuals.reverse()
        this.currentNs = row.ProjectAnnuals
        this.nsVisible = true
      } else {
        this.$message({
          type: 'warning',
          message: '暂无阶段评审记录'
        })
      }
    },
    recallOrder(row) {
      this.$confirm('是否确认撤回该申报?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.recallDisabled = true
        const recallParams = {
          work_oroder_id: row.id,
          process_id: row.process
        }
        recallWorkOrder(recallParams)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '撤回成功!'
              })
              this.recallDisabled = false
              this.initUsers()
            }
          })
          .catch(() => {
            this.recallDisabled = false
          })
      })
    },
    handleExportList() {
      this.downloadLoading = true
      const _this = this
      import('@/vendor/Export2Excel').then(async excel => {
        const tHeader = [
          '项目名称',
          '项目编号',
          '项目分类',
          '负责人姓名',
          '上报人',
          '上报人工号',
          '技术类别',
          '科室',
          '上报时间'
        ]
        const filterVal = [
          'title',
          'projectNo',
          'projectClassify',
          'leader_name',
          'user_name',
          'user_workno',
          'tech_type',
          'apply_depart',
          'create_time'
        ]
        const listData = await this.getAllList()
        for (let i = 0; i < listData.length; i++) {
          const jsonObj = JSON.parse(listData[i].form_data)
          listData[i].projectClassify = jsonObj['project_classify']
          listData[i].leader_name = jsonObj['leader_name']
          listData[i].user_name = jsonObj['user_name']
          listData[i].user_workno = jsonObj['user_workno']
          listData[i].tech_type = jsonObj['tech_type']
          listData[i].apply_depart = jsonObj['apply_depart']
          listData[i].leader_name = _this.userMap[jsonObj['leader_name']]
        }

        const data = formatJson(filterVal, listData)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '申报数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    handleExport(row) {
      this.downloadLoading = true
      const _this = this
      const jsonObj = JSON.parse(row.form_data)
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '项目名称',
          '项目编号',
          '项目分类',
          '负责人姓名',
          '上报人',
          '上报人工号',
          '技术类别',
          '科室',
          '上报时间'
        ]
        const filterVal = [
          'title',
          'projectNo',
          'projectClassify',
          'leader_name',
          'user_name',
          'user_workno',
          'tech_type',
          'apply_depart',
          'create_time'
        ]
        row.projectClassify = jsonObj['project_classify']
        row.leader_name = jsonObj['leader_name']
        row.user_name = jsonObj['user_name']
        row.user_workno = jsonObj['user_workno']
        row.tech_type = jsonObj['tech_type']
        row.apply_depart = jsonObj['apply_depart']

        row.leader_name = _this.userMap[jsonObj['leader_name']]

        const data = formatJson(filterVal, [row])
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: row.title + '-申报数据',
          autoWidth: true, // Optional
          bookType: 'xlsx' // Optional
        })
        this.downloadLoading = false
      })
    },
    resetQuery() {
      this.timeValue = ''
      this.resetForm('listQuery')
      this.getList()
    },
    getInitData() {
      projectData(this.queryList).then(response => {
        this.dashboardValue = response.data
      })
    },
    formatProjectClassify(val) {
      const jsonObj = JSON.parse(val)
      return jsonObj['project_classify']
    },
    formatLeaderName(val) {
      const jsonObj = JSON.parse(val)
      return this.userMap[jsonObj['leader_name']]
    },
    formatDepartName(val) {
      const jsonObj = JSON.parse(val)
      return jsonObj['apply_depart']
    },
    queryAllList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = undefined
      this.listQuery.status = undefined
      this.getList()
    },
    queryCompleteList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = 1
      this.listQuery.status = 0
      this.getList()
    },
    queryProcessList() {
      this.loading = true
      this.listQuery.page = 1
      this.listQuery.isEnd = 0
      this.listQuery.status = 0
      this.getList()
    },
    getList() {
      this.loading = true
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      } else {
        this.listQuery.startTime = this.parseTime(this.timeValue[0])
        this.listQuery.endTime = this.parseTime(this.timeValue[1])
      }
      this.listQuery.page = this.queryParams.pageIndex
      this.listQuery.per_page = this.queryParams.pageSize
      this.listQuery.classify = 6
      workOrderList(this.listQuery).then(response => {
        this.ticketList = response.data.data
        this.queryParams.pageIndex = response.data.page
        this.queryParams.pageSize = response.data.per_page
        this.total = response.data.total_count
        this.loading = false
      })
    },
    async getAllList() {
      const exportQuery = {}
      if (
        this.timeValue === null ||
        this.timeValue === undefined ||
        this.timeValue === ''
      ) {
        exportQuery.startTime = ''
        exportQuery.endTime = ''
      } else {
        exportQuery.startTime = this.parseTime(this.timeValue[0])
        exportQuery.endTime = this.parseTime(this.timeValue[1])
      }
      exportQuery.classify = 6
      exportQuery.page = 1
      exportQuery.per_page = 999999
      const res = await workOrderList(exportQuery)
      return res.data.data
    },

    handleView(row) {
      this.$refs.reviewDialog.open(row.process, row.id)
    },
    handleHistoryView(row) {
      this.$refs.historyDialog.open(row.process, row.id)
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          recyclingWorkOrder(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    handleUnity(row) {
      this.$confirm('此操作将会结束该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          unityWorkOrder({
            work_oroder_id: row.id
          }).then(response => {
            if (response.code === 200) {
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    initUsers() {
      listAllUser({}).then(response => {
        this.users = response.data
        for (let i = 0; i < this.users.length; i++) {
          const user = this.users[i]
          this.userMap[`${user.userId}`] = user.nickName
        }
        this.getInitData()
        this.getList()
      })
    },
    handleInversion(row) {
      this.dialogVisible = true
      this.ruleForm.work_order_id = row.id
      this.nodeList = row.state
      if (this.nodeList.length === 1) {
        this.ruleForm.node_id = this.nodeList[0].id
      }
      listAllUser({}).then(response => {
        this.users = response.data
      })
    },
    handleSelectionChange() { },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          inversionWorkOrder(this.ruleForm).then(response => {
            if (response.code === 200) {
              this.getList()
              this.dialogVisible = false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 12px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

::v-deep .el-tabs__item {
  padding-left: 16px !important;
  height: 50px;
  line-height: 50px;
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}

.leaderboard {
  height: 448px;
  overflow: auto;
}
</style>
